package com.cong.project.controller;

import com.cong.project.common.BaseResponse;
import com.cong.project.common.ErrorCode;
import com.cong.project.common.ResultUtils;
import com.cong.project.exception.BusinessException;
import com.cong.project.model.dto.ShopRankDto;
import com.cong.project.model.dto.TalkingRankDto;
import com.cong.project.model.enums.RankingEnum;
import com.cong.project.model.request.ProductAddRequest;
import com.cong.project.model.request.TokenUserRequest;
import com.cong.project.model.vo.ShopRankVo;
import com.cong.project.model.vo.TalkingRankVo;
import com.google.gson.Gson;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 排行榜控制器
 *
 * @author 86188
 * @date 2023/02/01
 */
@RestController
@RequestMapping("rank")
public class RankController {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 热谈排行榜前十
     * @return
     */
    @GetMapping("/talk")
    public BaseResponse talkRank(){
        List<TalkingRankVo> talkingRankVos = new ArrayList<>();
        /**
         *查看前十排名之间的记录有哪些
         */
        Set<ZSetOperations.TypedTuple<String>> tupleSet =
                stringRedisTemplate.opsForZSet().reverseRangeWithScores(RankingEnum.TALKING.getMessage(),0 ,9);
        tupleSet.forEach(item->{
            Gson gson = new Gson();
            TalkingRankDto talkingRankDto = gson.fromJson(item.getValue(), TalkingRankDto.class);
            TalkingRankVo talkingRankVo = new TalkingRankVo();
            BeanUtils.copyProperties(talkingRankDto,talkingRankVo);
            talkingRankVo.setThumbNum(item.getScore());
            talkingRankVos.add(talkingRankVo);
        });
        return ResultUtils.success(talkingRankVos);
    }

    /**
     * 热谈排行榜前十
     * @return
     */
    @GetMapping("/shop")
    public BaseResponse shopRank(){
        List<ShopRankVo> shopRankVos = new ArrayList<>();
        /**
         *查看前十排名之间的记录有哪些
         */
        Set<ZSetOperations.TypedTuple<String>> tupleSet =
                stringRedisTemplate.opsForZSet().reverseRangeWithScores(RankingEnum.SHOP.getMessage(),0 ,9);
        tupleSet.forEach(item->{
            Gson gson = new Gson();
            ShopRankDto shopRankDto = gson.fromJson(item.getValue(), ShopRankDto.class);
            ShopRankVo shopRankVo = new ShopRankVo();
            BeanUtils.copyProperties(shopRankDto,shopRankVo);
            shopRankVo.setFansNum((int) Math.round(item.getScore()));
            shopRankVos.add(shopRankVo);
        });
        return ResultUtils.success(shopRankVos);
    }
}
